﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// 生成分页导航
/// </summary>
public static class PageNav
{
	public static void BoundPage(Int32 totalCount,Int32 countPerPage,ref Int32 curPage)
	{
		if (curPage < 0)
			curPage = 0;
		else
		{
			Int32 mpi = (totalCount - 1) / countPerPage;
			if (curPage > mpi)
				curPage= mpi;
		}
	}
	public static String GenNav(
		Int32 totalCount,//总数量
		Int32 countPerPage,//每页显示的数量
		Int32 curPage,//当前页号
		Int32 pageNavCount,//导航页的数量
		String urlBegin//可以附带其他参数如?type=12& 或 a.aspx? 或 ?
		)
	{
		Int32 maxPageIndex = (totalCount-1) / countPerPage;//最大的页号
		if (maxPageIndex == 0)//只有一页，返回空
			return "";
		//确保当前页在范围内
		if (curPage < 0)
			curPage = 0;
		else if (curPage > maxPageIndex)
			curPage = maxPageIndex;
		String linkBegin="<a href='"+urlBegin+"cp=";
		System.Text.StringBuilder sbNav = new System.Text.StringBuilder();		
		sbNav.Append("<div class='pageNav'>前往页面：");		
		if (curPage > 0)
		{
			//显示第一页的导航链接
			sbNav.Append(linkBegin);
			sbNav.Append("0' >第一页</a>");
		}
		//开始的导航页号
		Int32 start = curPage - pageNavCount/2;
		if (start < 0)
			start = 0;
		//结束的导航页号
		Int32 end = start + pageNavCount - 1;
		if (end > maxPageIndex)
			end = maxPageIndex;
		//显示前pageNavCount/2个导航链接
		while (start < curPage)
		{
			sbNav.Append(linkBegin);
			sbNav.Append(start.ToString());
			sbNav.Append("'>[");
			sbNav.Append((start + 1).ToString());
			sbNav.Append("]</a>");
			++start;
		}
		//显示当前页的导航链接
		sbNav.Append((curPage + 1).ToString());
		//显示后pageNavCount/2个导航链接
		while (++start <= end)
		{
			sbNav.Append(linkBegin);
			sbNav.Append(start.ToString());
			sbNav.Append("'>[");
			sbNav.Append((start + 1).ToString());
			sbNav.Append("]</a>");
		}
		if (curPage < maxPageIndex)
		{
			//显示最后一页的导航链接
			sbNav.Append(linkBegin);
			sbNav.Append(maxPageIndex.ToString());
			sbNav.Append("'>最末页</a>");
		}
		sbNav.Append("</div>");
		return sbNav.ToString();
	}
}
